﻿using BaseUi.Tool;
using BaseUi.ViewModel;
using Microsoft.Win32;
using MySqlConnector;
using Ping9719.WpfEx;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Collections.Specialized.BitVector32;

namespace BaseUi
{
    /// <summary>
    /// 主页
    /// </summary>
    public partial class HomeView : UserControlBase
    {
        static readonly object locklog = new object();
        public static HomeViewModel viewModel = new HomeViewModel();
        private BarTender.Application btapp;
        public HomeView()
        {
            InitializeComponent();

            this.DataContext = viewModel;
            btapp = new BarTender.Application();
        }

        private void loadFir(object sender, EventArgs e)
        {
            if (this.IsInDesignMode)
                return;

            viewModel.LoadTask();
        }

        private void RunStateButClick(object sender, RoutedEventArgs e)
        {
            viewModel.RunStateClick((RunStateButtonClick)e.OriginalSource);
        }
        //private void keydown(object sender, KeyEventArgs e)
        //{
        //    if (e.Key == Key.Enter) {
        //        getbaoqian_Click(sender, e);
        //    }
        //}

        private void keydown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                try
                {
                    string code = TextBoxOuterModel.Text.Trim();
                    TextBoxOuterModel.Clear();
                    Task.Run(() =>
                    {
                        lock (locklog)
                        {
                            //string code = viewModel.IMEI;
                            viewModel.IMEI="";
                            string IMEI = "";
                            string ICCID = "";
                            string ID = "";
                            TextBoxLog.AddLog($"读取ID");
                            string getcode = "";
                            var data = new BoxInfo();
                            var dt = DateTime.Now;
                            string retul = "";
                            getcode=LocalStatic.ReadCode.sn();
                            if (getcode.Contains("报错"))
                            {
                                TextBoxLog.AddLog($"获取ID失败{getcode}");
                                return;
                            }
                            retul=pandunasn(getcode);
                            if (retul!="OK")
                            {
                                TextBoxLog.AddLog($"获取ID失败{retul}");
                            }
                            string[] splitid1 = getcode.Split(new string[] { "DEVID:" }, StringSplitOptions.RemoveEmptyEntries);
                            string[] splitid2 = splitid1[1].Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            if (splitid2[0].Length<2)
                            {
                                MessageBoxResult result = HandyControl.Controls.MessageBox.Show($"ID{splitid2[0]}长度为{splitid2[0].Length}，软件设置为{LocalFile.Config.IDL}取消打印", null, MessageBoxButton.OKCancel, MessageBoxImage.None, MessageBoxResult.Cancel);
                                TextBoxLog.AddLog($"ID{splitid2[0]}长度为{splitid2[0].Length}，软件设置为{LocalFile.Config.IDL}取消打印");
                                return;
                            }
                            ID=splitid2[0].Substring(1, splitid2[0].Length-1);
                            if (ID.Length!=LocalFile.Config.IDL)
                            {
                                MessageBoxResult result = HandyControl.Controls.MessageBox.Show($"ID{ID}长度为{ID.Length}，软件设置为{LocalFile.Config.IDL}取消打印", null, MessageBoxButton.OKCancel, MessageBoxImage.None, MessageBoxResult.Cancel);
                                TextBoxLog.AddLog($"ID{ID}长度为{ID.Length}，软件设置为{LocalFile.Config.IDL}取消打印");
                                IMEI="";
                                return;
                            }
                            if (ID!=code)
                            {
                                MessageBoxResult result = HandyControl.Controls.MessageBox.Show($"扫描ID{code}与通信{ID}，取消打印", null, MessageBoxButton.OKCancel, MessageBoxImage.None, MessageBoxResult.Cancel);
                                TextBoxLog.AddLog($"扫描ID{code}与通信{ID}，取消打印");
                                return;
                            }
                            TextBoxLog.AddLog($"读取ICC");
                            getcode=LocalStatic.ReadCode.icc();
                            if (getcode.Contains("报错"))
                            {
                                TextBoxLog.AddLog($"获取ICC失败{getcode}");
                                return;
                            }
                            retul=pandunaicc(getcode);
                            if (retul!="OK")
                            {
                                TextBoxLog.AddLog($"获取ICC失败{retul}");
                            }
                            string[] spliticc1 = getcode.Split(new string[] { "ICCID:" }, StringSplitOptions.RemoveEmptyEntries);
                            string[] spliticc2 = spliticc1[1].Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            ICCID=spliticc2[0];
                            if (ICCID.Length!=LocalFile.Config.ICCL)
                            {
                                MessageBoxResult result = HandyControl.Controls.MessageBox.Show($"ICCID{ICCID}长度为{ICCID.Length}，软件设置为{LocalFile.Config.ICCL}取消打印", null, MessageBoxButton.OKCancel, MessageBoxImage.None, MessageBoxResult.Cancel);
                                TextBoxLog.AddLog($"ICCID{ICCID}长度为{ICCID.Length}，软件设置为{LocalFile.Config.ICCL}取消打印");
                                IMEI="";
                                return;
                            }
                            TextBoxLog.AddLog($"读取IMEI");
                            getcode=LocalStatic.ReadCode.imei();
                            if (getcode.Contains("报错"))
                            {
                                TextBoxLog.AddLog($"获取IMEI失败{getcode}");
                                return;
                            }
                            retul=pandunaimei(getcode);
                            if (retul!="OK")
                            {
                                TextBoxLog.AddLog($"获取IMEI失败{retul}");
                            }
                            string[] splitimei1 = getcode.Split(new string[] { "IMEI:" }, StringSplitOptions.RemoveEmptyEntries);
                            string[] splitimei2 = splitimei1[1].Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            IMEI=splitimei2[0];
                            if (IMEI.Length!=LocalFile.Config.IMEIL)
                            {
                                MessageBoxResult result = HandyControl.Controls.MessageBox.Show($"IMEI{IMEI}长度为{IMEI.Length}，软件设置为{LocalFile.Config.IMEIL}取消打印", null, MessageBoxButton.OKCancel, MessageBoxImage.None, MessageBoxResult.Cancel);
                                TextBoxLog.AddLog($"IMEI{IMEI}长度为{IMEI.Length}，软件设置为{LocalFile.Config.IMEIL}取消打印");
                                IMEI="";
                                return;
                            }
                            List<BoxInfo> List = DataDb.dbBox.Queryable<BoxInfo>().
                        Where(it => it.Time >= DateTime.Today.AddDays(-7)&&it.IMEI == IMEI).ToList();
                            if (List.Count > 0)
                            {
                                MessageBoxResult result = HandyControl.Controls.MessageBox.Show($"{IMEI}重复，是否需要重复打印？", null, MessageBoxButton.OKCancel, MessageBoxImage.None, MessageBoxResult.Cancel);
                                if (result == MessageBoxResult.Cancel)
                                {
                                    TextBoxLog.AddLog($"{IMEI}重复，取消打印");
                                    return;
                                }
                                else
                                {
                                    data.repeat="重复"+List[0].Time;
                                }
                            }
                            else
                            {
                                data.repeat="";
                            }
                            data.IMEI=IMEI;
                            data.VID=ID;
                            data.ICC=ICCID;
                            data.Time = dt;
                            data.Name = UserInfoView.viewModel.LoginName;
                            data.Remarks="";
                            DataDb.dbBox.Insertable(data).ExecuteCommand();
                            ApplicationTool.ProRePrint(btapp, LocalFile.Config.PrintModel, data);
                            TextBoxLog.AddLog($"标签打印完成IMEI{IMEI},ID{ID},ICC{ICCID}{data.repeat}");
                            OutputStatChartView.viewModel.UpdataData();
                        }
                    });
                }
                catch (Exception ee)
                {
                    TextBoxLog.AddLog($"打印异常{ee.ToString()}");
                }
                finally
                {
                    OutputStatChartView.viewModel.UpdataData();

                }
            }


        }

       

        private string pandunaimei(string getcode)
        {
            if (getcode.Length==0)
            {
                return "串口未接收到信息";
            }
            if (!getcode.Contains("IMEI")||!getcode.Contains("OK"))
            {
                return "串口未接收到完整信息";
            }
            return "OK";
        }
        private string pandunasn(string getcode)
        {
            if (getcode.Length==0)
            {
                return "串口未接收到信息";
            }
            if (!getcode.Contains("DEVID")||!getcode.Contains("OK"))
            {
                return "串口未接收到完整信息";
            }
            return "OK";
        }
        private string pandunaicc(string getcode)
        {
            if (getcode.Length==0)
            {
                return "串口未接收到信息";
            }
            if (!getcode.Contains("ICCID")||!getcode.Contains("OK"))
            {
                return "串口未接收到完整信息";
            }
            return "OK";
        }

        private void getbaoqian_Click1(object sender, RoutedEventArgs e)
        {
            try
            {
                ApplicationTool.ProcsRePrint(btapp, LocalFile.Config.PrintModel);
                //string str = ApplicationTool.PrintWithCsvDDL(
                //    AppDomain.CurrentDomain.BaseDirectory +"cs.dll",
                //    new Dictionary<string, string>
                //    {
                //        ["csname"] = "15984814566",
                //    },
                //    LocalFile.Config.Patth+"\\DLabel.exe"
                ////"D:\\Dlabel\\DLabel.exe"
                //);
                //if (str!="OK")
                //{
                //    TextBoxLog.AddLog($"测试打印异常{str}");
                //}
            }
            catch (Exception ee)
            {

                TextBoxLog.AddLog($"测试打印异常{ee.ToString()}");
            }
        }
    }
}
